package com.easylinkin.linkappapi.security.controller.admin;

import static com.easylinkin.linkappapi.security.constant.admin.UserConstant.ADMIN_LOGIN_VERIFICATION_CODE_PREFIX;

import com.easylinkin.bases.redis.util.RedisUtil;
import com.easylinkin.linkappapi.common.utils.message.SendMessageUtil;
import com.easylinkin.sm.entity.User;
import com.easylinkin.sm.service.UserService;
import io.swagger.annotations.Api;
import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import site.morn.boot.data.DisplayableControllerSupport;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

/**
 * 用户控制器
 *
 * @author tongjie
 * @since 2021/2/23
 */
@Api(tags = "管理端用户管理")
@RestController
@RequestMapping("/adminUser")
public class AdminUserController extends DisplayableControllerSupport<User, Long, UserService> {

    @Resource
    RedisUtil redisUtil;
    @Resource
    SendMessageUtil sendMessageUtil;
    @Value("${linkapp.isEnableVerificationCode:true}")
    private Boolean isEnableVerificationCode;

    @RequestMapping("/verificationCode")
    public RestMessage verificationCode(@RequestParam("username") String username) {
        User user = service().findByUsername(username);
        Assert.notNull(user, "通过用户名查找不到用户");
        String phone = user.getPhone();
        Assert.hasLength(phone, "用户未绑定手机号");
        int randomInt = (int) ((Math.random() * 999999));
        String randomNo = String.format("%6d", randomInt).replace(" ", "0");
        redisUtil.set(ADMIN_LOGIN_VERIFICATION_CODE_PREFIX + username, randomNo, 300);
        sendMessageUtil.sendVerificationCode(phone, randomNo);
        return RestBuilders.successMessage();
    }

    @RequestMapping("isEnableVerificationCode")
    public RestMessage isEnableVerificationCode() {
        return RestBuilders.successMessage(isEnableVerificationCode);
    }

}
